/*字符串替换省略号*/
function cutString(str, len) {
  if (str.length * 2 <= len) {
    return str;
  }
  var strlen = 0;
  var s = "";
  for (var i = 0; i < str.length; i++) {
    s = s + str.charAt(i);
    if (str.charCodeAt(i) > 128) {
      strlen = strlen + 2;
      if (strlen >= len) {
        return s.substring(0, s.length - 1) + "...>";
      }
    } else {
      strlen = strlen + 1;
      if (strlen >= len) {
        return s.substring(0, s.length - 2) + "...>";
      }
    }
  }
  return s;
}
function showToast(obj, txt) {
  obj.setData({
    $toast: {
      show: true,
      text: txt
    }
  })
  setTimeout(() => {
    obj.setData({
      $toast: {
        show: false
      }
    })
  }, 1500)
}
function scan(self, common) {
  wx.scanCode({
    onlyFromCamera: true,
    success: (res) => {
      if (res.result.length != 10 && res.result.length != 13) {
        common.showToast(self, '请扫正确的图书条形码')
      } else {
        wx.redirectTo({ 'url': `../coderesults/index?results=${res.result}` })
      }
    },
    fail: (res) => {
      common.showToast(self, '扫码失败')
    }
  })
}
//检查日期
function DateDiff(sDate1, sDate2) {    //sDate1和sDate2是2002-12-18格式  
  var aDate, oDate1, oDate2, iDays
  aDate = sDate1.split("-")
  oDate1 = new Date(aDate[1] + '-' + aDate[2] + '-' + aDate[0])    //转换为12-18-2002格式  
  aDate = sDate2.split("-")
  oDate2 = new Date(aDate[1] + '-' + aDate[2] + '-' + aDate[0])
  iDays = parseInt(Math.abs(oDate1 - oDate2) / 1000 / 60 / 60 / 24)    //把相差的毫秒数转换为天数  
  return iDays
}
function getTime() {
  var date = new Date();
  var year = date.getFullYear();
  var month = date.getMonth() + 1;
  var day = date.getDate();
  if (month < 10) {
    month = "0" + month;
  }
  if (day < 10) {
    day = "0" + day;
  }
  var nowDate = year + "-" + month + "-" + day;
  return nowDate
}



function deepClone(obj) {
  let objClone = Array.isArray(obj) ? [] : {};
  if (obj && typeof obj === "object") {
    for (let key in obj) {
      if (obj.hasOwnProperty(key)) {
        //判断ojb子元素是否为对象，如果是，递归复制
        if (obj[key] && typeof obj[key] === "object") {
          objClone[key] = deepClone(obj[key]);
        } else {
          //如果不是，简单复制
          objClone[key] = obj[key];
        }
      }
    }
  }
  return objClone;
}
module.exports = {
  cutString,
  showToast,
  scan,
  DateDiff,
  getTime,
  deepClone
}